package com.demo.utils;


import org.apache.log4j.Logger;
import org.apache.poi.util.IOUtils;
import org.springframework.core.io.ClassPathResource;

import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;
/**
 * 工具类
 */
public class CommonUtils {
    private static final Logger logger = Logger.getLogger(CommonUtils.class);
    /**
     * 从指定路径的文件获取sql语句
     * @param rs
     * @return
     */
    public static String getSqlFromFile(final ClassPathResource rs) {
        try {
            return new String(IOUtils.toByteArray(rs.getInputStream()));
        } catch (IOException e) {
            return null;
        }
    }

    /**
     * 将Object对象里面的属性和值转化成Map对象
     *
     * @param obj
     * @return
     * @throws IllegalAccessException
     */
    public static Map<String, Object> objectToMap(Object obj) throws IllegalAccessException {
        Map<String, Object> map = new HashMap<String,Object>();
        Class<?> clazz = obj.getClass();
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            String fieldName = field.getName();
            Object value = field.get(obj);
            map.put(fieldName, value);
        }
        return map;
    }

    /**
     * 将List里对象转化成Map对象
     *
     * @param objList
     * @return
     * @throws IllegalAccessException
     */
    public static List<Map<String, Object>> listObjectToListMap(List objList) throws IllegalAccessException {
        if(null==objList||objList.size()==0){
            return null;
        }
        List<Map<String, Object>> mapList=new ArrayList<>();
        for(Object o:objList){
            mapList.add(objectToMap(o));
        }
        return mapList;
    }

    public static Date setQueryStartDateIncluded(Date startDate) {
        if (startDate == null) {
            return null;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(startDate);
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE), 0, 0, 0);
        return calendar.getTime();
    }

    public static Date setQueryEndDateIncluded(Date endDate) {
        if (endDate == null) {
            return null;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(endDate);
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE), 23, 59, 59);
        return calendar.getTime();
    }


    /**
     * 将字符串转换成驼峰命名的格式
     * @param colName
     * @return
     */
    public static String toFormatCol(String colName) {
        //StringBuilder便于添加新的字符段
        StringBuilder sb = new StringBuilder();
        //用正则分割
        String[] str = colName.split("_");
        int i = 0;
        //遍历
        for (String s : str) {
            if (s.length() == 1) {
                //单独字母的都大写
                s = s.toUpperCase();
            }
            i++;
            //首字母不需要大写-根据驼峰命名规则进行大小写判断并转换
            if (i == 1) {
                //第一个单词不需要大写  直接加入
                sb.append(s);
                //第一个
                continue;
            }
            if (s.length() > 0) {
                //将单词的第一个字母拿出并大写，并拼接
                sb.append(s.substring(0, 1).toUpperCase());
                //将除首字母外的字母拼接其后
                sb.append(s.substring(1));
            }
        }
        //转化成String并返回值
        return sb.toString();
    }

    public static Map<String, Map<String,Object>> compareFields(Object oldObject, Object newObject) {
        //定义map集合
        Map<String, Map<String,Object>> map = new HashMap<>();
        //存放前值的集合
        Map<String,Object> oldMap;
        //存放后值的集合
        Map<String,Object> newMap;
        try {
            oldMap = new HashMap<>();
            newMap = new HashMap<>();
            //获取oldObject的所有属性
            PropertyDescriptor[] oldPds = Introspector.getBeanInfo(oldObject.getClass(),Object.class)
                    .getPropertyDescriptors();
            for (PropertyDescriptor oldPd : oldPds) {
                //遍历获取属性名
                String name = oldPd.getName();
                //获取属性的get方法
                Method readMethod = oldPd.getReadMethod();
                //获得oldObject的属性值
                Object oldValue = readMethod.invoke(oldObject);
                //获得newObject的属性值
                Object newValue = readMethod.invoke(newObject);
                if(oldValue==null&&newValue==null){
                    continue;
                }
                if(!Objects.equals(oldValue,newValue)){
                    oldMap.put(name,oldValue);
                    newMap.put(name,newValue);
                }
            }
            map.put("oldMap", oldMap);
            map.put("newMap", newMap);
        } catch (Exception e) {
            logger.warn("访问compareFields出现异常",e);
        }
        return map;
    }
}
